package com.studerb.tests.integration;

import java.awt.Component;
import java.util.EventObject;

import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.Application.ExitListener;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class GnusbinTestApp extends SingleFrameApplication {
	private static final Logger logger = Logger.getLogger(GnusbinTestApp.class);
	protected static AbstractApplicationContext springAppContext;
	private JComponent mainTestPanel;

	/* (non-Javadoc)
	 * @see org.jdesktop.application.Application#startup()
	 * Start up the Gui
	 */
	@Override protected void startup() {
		addExitListener(new ConfirmExitListener());
		mainTestPanel = (JComponent) springAppContext.getBean("mainTestPanel");
		show(mainTestPanel);
	}

	@Override protected void shutdown() {
		logger.debug("Shutting Down");
		super.shutdown();
		logger.debug("Closing Spring AppContext");
		GnusbinTestApp.springAppContext.close();
	}

	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			logger.debug("Starting Spring Application Context");
			springAppContext = new ClassPathXmlApplicationContext(
					new String[] { "classpath:testApplicationContext.xml" });
			springAppContext.registerShutdownHook();
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println(ExceptionUtils.getRootCauseMessage(e));
			System.exit(1);
		}
		try {
			Application.launch(GnusbinTestApp.class, null);
		} catch (Exception e) {
			Application.getInstance(GnusbinTestApp.class).end();
		}
	}
}

class ConfirmExitListener implements ExitListener {
	@Override public boolean canExit(EventObject e) {
		Object source = (e != null) ? e.getSource() : null;
		Component owner = (source instanceof Component) ? (Component) source : null;
		int option = JOptionPane.showConfirmDialog(owner, "Really Exit?");
		return option == JOptionPane.YES_OPTION;
	}

	@Override public void willExit(EventObject e) {}
}
